package com.leyou.common.util;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zqq
 * @ClassName CloneUtils
 * @Description: 对象克隆->对性能有影响，慎用
 * @date 2020/3/5-10:52
 */
public class CloneUtils {

    /**
     * @param source    源对象
     * @param classType 需要拷贝的对象
     * @Title: clone
     * @Description: 克隆对象
     * @author: zqq
     * @return: E
     * @createTime: 2020-03-05 10:52
     * @version: v.1.0
     */
    public static <T, E> E clone(T source, Class<E> classType) {
        if (source == null) {
            return null;
        }
        E targetInstance = null;
        try {
            targetInstance = classType.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        BeanUtils.copyProperties(source, targetInstance);
        return targetInstance;
    }

    /**
     * @param sourceList 源集合对象
     * @param classType  需要拷贝的对象
     * @Title: batchClone
     * @Description: 克隆集合对象
     * @author: zqq
     * @return: java.util.List<E>
     * @createTime: 2020-03-05 10:53
     * @version: v.1.0
     */
    public static <T, E> List<E> batchClone(List<T> sourceList, Class<E> classType) {
        if (sourceList == null) {
            return null;
        }
        List<E> result = new ArrayList<E>();
        int size = sourceList.size();
        for (int i = 0; i < size; i++) {
            result.add(clone(sourceList.get(i), classType));
        }
        return result;
    }
}
